package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.entity.SwStPlanDay;
import com.zdkj.subway.st.entity.SwStPlanWeek;
import com.zdkj.subway.st.service.SwStPlanDayService;
import com.zdkj.subway.st.service.SwStPlanWeekService;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import com.zdkj.subway.st.util.SubwayStConstants;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@AllArgsConstructor
@RequestMapping("/swStPlanWeek")
@Api(value = "swStPlanWeek", tags = "周计划管理")
@Slf4j
public class SwStPlanWeekController {
    private final SwStPlanWeekService swStPlanWeekService;
    private final SwStPlanDayService swStPlanDayService;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStPlanWeekService.getById(id));
    }

    @GetMapping("/page/{type}")
    public R<IPage> getDictPage(Page page, SwStPlanWeek swStPlanWeek, @PathVariable String type) {
        swStPlanWeek.setPlanType(type);
        /*LambdaQueryWrapper<SwStPlanWeek> lambdaQueryWrapper = Wrappers.lambdaQuery(swStPlanWeek)
                .eq(SwStPlanWeek::getDisplay, true);*/
        String numbers = swStPlanWeek.getNumbers();
        swStPlanWeek.setNumbers(null);
        QueryWrapper<SwStPlanWeek> lambdaQueryWrapper = Wrappers.query(swStPlanWeek);
        lambdaQueryWrapper.lambda().eq(SwStPlanWeek::getDisplay, true);
        if(StringUtils.isNotEmpty(numbers)){
            lambdaQueryWrapper.lambda().like(SwStPlanWeek::getNumbers,numbers);
        }
        lambdaQueryWrapper.orderByDesc("CREATE_TIME");
        return R.ok(swStPlanWeekService.page(page, lambdaQueryWrapper));
    }
    @GetMapping("/pages/{type}")
    public R<IPage> getMonthForPage(Page page, SwStPlanWeek swStPlanWeek, @PathVariable String type) {
        swStPlanWeek.setPlanType(type);
        LambdaQueryWrapper<SwStPlanWeek> lambdaQueryWrapper = Wrappers.lambdaQuery(swStPlanWeek);
        return R.ok(swStPlanWeekService.page(page, lambdaQueryWrapper));
    }

    @SysLog("新增车票周计划")
    @PostMapping
    public R save(@Valid @RequestBody SwStPlanWeek swStPlanWeek) {
        PigxUser user = SecurityUtils.getUser();
        swStPlanWeek.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
        swStPlanWeek.setCreatorId((long) user.getId());
        swStPlanWeek.setCreatorName(user.getUsername());
        swStPlanWeek.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
        return R.ok(swStPlanWeekService.save(swStPlanWeek));
    }

    @SysLog("批量新增车票周计划")
    @PostMapping("/saveAll")
    public R saveAll(@Valid @RequestBody List<SwStPlanWeek> swStPlanWeekList) {
        PigxUser user = SecurityUtils.getUser();
        for (SwStPlanWeek swStPlanWeek : swStPlanWeekList) {
            swStPlanWeek.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
            swStPlanWeek.setCreatorId((long) user.getId());
            swStPlanWeek.setCreatorName(user.getUsername());
            swStPlanWeek.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
            swStPlanWeekService.save(swStPlanWeek);
        }
        return R.ok(swStPlanWeekList.size());
    }

    @SysLog("删除车票周计划")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable String id) {
        return R.ok(swStPlanWeekService.removeById(id));
    }

    @PutMapping
    @SysLog("修改车票周计划")
    public R updateById(@Valid @RequestBody SwStPlanWeek swStPlanWeek) {
        if(!Objects.equals(swStPlanWeek.getPlanNumberNow(),swStPlanWeek.getPlanNumberOld())){
            swStPlanWeek.setWhetherStatus("1");
        }else{
            swStPlanWeek.setWhetherStatus("0");
        }
        return R.ok(swStPlanWeekService.updateById(swStPlanWeek));
    }
    @PutMapping("/{id}/decompose")
    @SysLog("分解车票周计划")
    public R decompose(@PathVariable Long id, @Valid @RequestBody List<SwStPlanDay> planDays) {
        if(!swStPlanWeekService.decompose(id, planDays)){
            return R.failed("分解计划明细不能为空/或者已分解完成的计划不能在分解");
        }else{
            return R.ok(swStPlanWeekService.decompose(id, planDays));
        }
    }

    @PutMapping("/{id}/updateDecompose")
    @SysLog("修改分解车票周计划信息")
    public R updateDecompose(@PathVariable Long id, @Valid @RequestBody List<SwStPlanDay> planDays) {
        return R.ok(swStPlanWeekService.updateDecompose(id, planDays));
    }

    @PutMapping("/submit")
    @SysLog("提交车票周计划")
    public R submit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanWeekService.submitBatch(ids));
    }

    /*@PutMapping("/audit")
    @SysLog("审批车票周计划")
    public R audit(@Valid @RequestBody SwStAuditDTO swStAuditDTO) {
        return R.ok(swStPlanWeekService.auditBatch(swStAuditDTO));
    }*/
    @PutMapping("/audit")
    @SysLog("审批车票周计划")
    public R audit(@Valid @RequestBody SwStPlanWeek swStPlanWeek) {
        PigxUser user = SecurityUtils.getUser();
        swStPlanWeek.setCheckPersonId(user.getId());
        swStPlanWeek.setCheckTime(LocalDateTime.now());
        if(SubwayStConstants.AUDIT_STATUS_PASS.equals(swStPlanWeek.getCheckStatus())){
            swStPlanDayService.update(Wrappers.<SwStPlanDay>lambdaUpdate()
                    .eq(SwStPlanDay::getPlanWeekId, swStPlanWeek.getId())
                    .set(SwStPlanDay::getDisplay, true));
        }
        return R.ok(swStPlanWeekService.updateById(swStPlanWeek));
    }


    @GetMapping("/export")
    @SysLog("导出车票周计划")
    public void exportExcel(SwStPlanWeek swStPlanWeek, HttpServletResponse response) throws IOException {
        List<SwStPlanWeek> swStCycleList = swStPlanWeekService.list(Wrappers.query(swStPlanWeek));
        String fileName = URLEncoder.encode("车票周计划", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStPlanWeek.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票周计划").doWrite(swStCycleList);
    }
    /*@GetMapping("/export")
    @SysLog("导出车票周计划")
    public void exportExcel(SwStPlanWeek swStPlanWeek, HttpServletResponse response) throws IOException {
        List<SwStPlanWeek> swStCycleList = swStPlanWeekService.list(Wrappers.query(swStPlanWeek));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swStCycleList);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("", e);
        }
    }*/

}
